package com.demo.rocketmq.producer;

import com.demo.rocketmq.config.RocketMqConfig;
import com.demo.rocketmq.config.ProducerConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.AccessChannel;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class DemoProducer {


    @Autowired
    private RocketMqConfig rocketMqConfig;
    @Autowired
    private ProducerConfig rocketMqProducerConfig;



    @Bean(initMethod = "start", destroyMethod = "shutdown")
    public DefaultMQProducer defaultMQProducer() {

        DefaultMQProducer producer;
        if (rocketMqConfig.getAclActive()) {
            // 生产环境使用阿里云mq
            producer = new DefaultMQProducer(rocketMqConfig.getDefaultProducerGroup(), rocketMqConfig.getAclRPCHook(), true, null);
            // 设置使用接入方式为阿里云，在使用云上消息轨迹的时候，需要设置此项，如果不开启消息轨迹功能，则运行不设置此项。
            producer.setAccessChannel(AccessChannel.CLOUD);
        } else {
            producer = new DefaultMQProducer(rocketMqConfig.getDefaultProducerGroup());
        }
        log.info("《====================【rocketmq初始化配置】====================》");
        log.info("aclActive = {}", rocketMqConfig.getAclActive());
        log.info("accessKey = {}", rocketMqConfig.getAccessKey());
        log.info("secretKey = {}", rocketMqConfig.getSecretKey());
        log.info("namesrvAddr = {}", rocketMqConfig.getNamesrvAddr());
        log.info("defaultProducerGroup = {}", rocketMqConfig.getDefaultProducerGroup());
        log.info("maxMessageSize = {}", rocketMqProducerConfig.getMaxMessageSize());
        log.info("sendMsgTimeout = {}", rocketMqProducerConfig.getSendMsgTimeout());
        log.info("retryTimesWhenSendFailed = {}", rocketMqProducerConfig.getRetryTimesWhenSendFailed());
        // 如果需要同一个jvm中不同的producer往不同的mq集群发送消息，需要设置不同的instanceName
        // producer.setInstanceName(instanceName);
        producer.setNamesrvAddr(rocketMqConfig.getNamesrvAddr());
        producer.setMaxMessageSize(rocketMqProducerConfig.getMaxMessageSize());
        producer.setSendMsgTimeout(rocketMqProducerConfig.getSendMsgTimeout());
        producer.setRetryTimesWhenSendFailed(rocketMqProducerConfig.getRetryTimesWhenSendFailed());
        log.info("《====================【rocketmq生产者启动成功】====================》");
        return producer;
    }

}